import axios from 'axios';
import common from '@/commons/common.js';
import { Message } from 'element-ui';
window.app.axios = axios;
let http = axios.create({
    withCredentials: true,
    timeout: 1800000
});

function apiAxios(method, url, params, response, headers, hostName, responseType) {
    http({
        method: method,
        url: hostName === null || hostName === undefined ? window.config.host + url : hostName + url,
        data: method === 'POST' || method === 'PUT' ? params : null,
        params: method === 'GET' || method === 'DELETE' ? params : null,
        headers: headers !== undefined && headers != null ? headers : null,
        responseType: responseType === undefined ? '' : responseType
    })
        .then(function(res) {
            if (res === null || res === undefined) {
                return;
            }

            if(res.data.code == 50003){
                sessionStorage.removeItem('token')
                window.location.href = window.location.origin + window.location.pathname + '#/login'
                return
            }


            if (
                res.data.statusCode === common.requestCode.ERROR_PASSWORD &&
                res.config.url.indexOf('authCtrl/login') < 0 &&
                res.config.url.indexOf('/auth/authCtrl/changePassword') < 0 &&
                res.config.url.indexOf('/auth/authCtrl/haveAllPermission') < 0
            ) {
                Message.error(window.i18n.t('common.LOG_IN_AGAIN'));
            }
            response(res);
        })
        .catch(function(err) {
            if (err.message == "Cannot read property '_t' of null") {
                return;
            }
            // let data = {
            //     statusCode: 'API_ERROR',
            //     statusMessage: window.i18n.t('error.ERROR_API')
            // };
            if (err.response) {
                // err.response.data = data;
                response(err.response);
            } else {
                // err.data = data;
                response(err);
            }
        });
}
// 获取操作位置信息
function getMethodLoacation(obj) {
    var re;
    if (obj && obj.nodeType === 1) {
        if (checkNodeType(obj, 'button') || (checkNodeType(obj, 'span') && obj.innerText == obj.innerHTML)) {
            re = obj.innerText;
        } else if (checkNodeType(obj, 'div') && obj.attributes && obj.attributes['role'] && obj.attributes['role'].textContent === 'dialog' && obj.attributes['aria-label']) {
            re = obj.attributes['aria-label'].textContent + '弹窗';
        }
    }
    return re;
}
// 验证类型是否匹配
function checkNodeType(obj, type) {
    if (obj && type) {
        if (obj.tagName && obj.tagName.toLowerCase() === type) {
            return true;
        }
        if (obj.type && obj.type.toLowerCase() === type) {
            return true;
        }
    }
    return false;
}
// 验证菜单及位置名称
function getMenuName(operationLocation) {
    let titles = operationLocation;
    if (!operationLocation || operationLocation == '') {
        var evtTarget = window.event != null ? window.event.target || window.event.srcElement : null;
        titles = [];
        while (evtTarget) {
            var title = getMethodLoacation(evtTarget);
            if (title && title != null) {
                titles.unshift(title);
            }
            evtTarget = evtTarget.parentNode;
        }
        if (!evtTarget) {
            getConfirmLoacation(titles);
        }
        if (titles) {
            getMenu(titles);
            let set = new Set(titles);
            titles = Array.from(set);
            titles = titles.join('-');
        } else {
            titles = 'init';
        }
    }

    return titles;
}
// 有confirm的事件获取位置
function getConfirmLoacation(titles) {
    var list = window.eventTarget != null ? window.eventTarget.parentNodeList : null;
    if (list) {
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            var title = getMethodLoacation(item);
            if (title && title != null) {
                titles.unshift(title);
            }
        }
    } else {
        titles = null;
    }
    window.eventTarget = null;
}
// 验证类型是否匹配
function getMenu(titles) {
    if (window.getCurrentMenu) {
        if (window.getCurrentMenu() != null) {
            titles.unshift(window.getCurrentMenu());
        }
    } else if (window.parent == window && parent.getCurrentMenu) {
        if (parent.getCurrentMenu() != null) {
            titles.unshift(parent.getCurrentMenu());
        }
    }
}

export default {
    get: function(url, params, response, hostName, operationLocation, token) {
        let headers = {
            token: token ? token : sessionStorage.getItem('token'),
            operationLocation: encodeURI(encodeURI(getMenuName(operationLocation)))
        };
        let t = '?t=' + new Date().getTime();
        if (/\?/g.test(url)) {
            t = '&t=' + new Date().getTime();
        }
        url = url + t;
        return apiAxios('GET', url, params, response, headers, hostName);
    },
    post: function(url, params, response, hostName, operationLocation, token) {
        let headers = {
            token: token ? token : sessionStorage.getItem('token'),
            operationLocation: encodeURI(encodeURI(getMenuName(operationLocation)))
        };
        let t = '?t=' + new Date().getTime();
        if (/\?/g.test(url)) {
            t = '&t=' + new Date().getTime();
        }
        url = url + t;
        return apiAxios('POST', url, params, response, headers, hostName);
    },
    postRequestBody: function(url, params, response, hostName, operationLocation, token) {
        let headers = {
            'Content-Type': 'application/json;charset=UTF-8',
            token: token ? token : sessionStorage.getItem('token'),
            operationLocation: encodeURI(encodeURI(getMenuName(operationLocation)))
        };
        let t = '?t=' + new Date().getTime();
        if (/\?/g.test(url)) {
            t = '&t=' + new Date().getTime();
        }
        url = url + t;
        return apiAxios('POST', url, params, response, headers, hostName);
    },
    put: function(url, params, response, hostName, operationLocation, token) {
        let headers = {
            token: token ? token : sessionStorage.getItem('token'),
            operationLocation: encodeURI(encodeURI(getMenuName(operationLocation)))
        };
        let t = '?t=' + new Date().getTime();
        if (/\?/g.test(url)) {
            t = '&t=' + new Date().getTime();
        }
        url = url + t;
        return apiAxios('PUT', url, params, response, headers, hostName);
    },
    delete: function(url, params, response, hostName, operationLocation, token) {
        let headers = {
            token: token ? token : sessionStorage.getItem('token'),
            operationLocation: encodeURI(encodeURI(getMenuName(operationLocation)))
        };
        let t = '?t=' + new Date().getTime();
        if (/\?/g.test(url)) {
            t = '&t=' + new Date().getTime();
        }
        url = url + t;
        return apiAxios('DELETE', url, params, response, headers, hostName);
    },
    download: function(url, params, responseType, response, hostName, operationLocation, token) {
        let headers = {
            token: token ? token : sessionStorage.getItem('token'),
            operationLocation: encodeURI(encodeURI(getMenuName(operationLocation)))
        };
        let t = '?t=' + new Date().getTime();
        if (/\?/g.test(url)) {
            t = '&t=' + new Date().getTime();
        }
        url = url + t;
        return apiAxios('GET', url, params, response, headers, hostName, responseType);
    },
    downloadPost: function(url, params, responseType, response, hostName, operationLocation, token) {
        let headers = {
            token: token ? token : sessionStorage.getItem('token'),
            operationLocation: encodeURI(encodeURI(getMenuName(operationLocation)))
        };
        let t = '?t=' + new Date().getTime();
        if (/\?/g.test(url)) {
            t = '&t=' + new Date().getTime();
        }
        url = url + t;
        return apiAxios('POST', url, params, response, headers, hostName, responseType);
    },
    // 获取操作位置名称
    getoperationLocation(operationLocation) {
        return getMenuName(operationLocation);
    },
    axios(method, url, params, response, headers, hostName, responseType) {
        return apiAxios(method, url, params, response, headers, hostName, responseType);
    }
};
